<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="showTitle" :visible="dialogVisible" @close="handlerClose">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="deptForm" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @focus="handlerFocus">
          <el-option v-for="item in people" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="handlerSubmit">确定</el-button>
        <el-button size="small" @click="handlerClose">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
// - 部门名称（name）：必填 1-50个字符  / 同级部门中禁止出现重复部门
// - 部门编码（code）：必填 1-50个字符  / 部门编码在整个模块中都不允许重复
// - 部门负责人（manager）：必填
// - 部门介绍 ( introduce)：必填 1-300个字符
import { getDepartmentsApi, addDepartmentsApi, updateDepartmentsApi } from '@/api/departments'
import { getEmployeeSimpleApi } from '@/api/employees'
export default {
  props: {
    dialogVisible: Boolean,
    currentNode: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const checkCode = async(rule, value, callback) => {
      // console.log(rule, value, callback) // 校验规则 值 回调
      const { depts } = await getDepartmentsApi()
      let flag
      if (this.formData.id) {
        // 编辑模式下先排除自己，在判断是否有重复
        flag = depts.some(ele => ele.id !== this.currentNode.id && ele.code === value)
      } else {
        flag = depts.some(ele => ele.code === value)
      }
      flag ? callback(new Error(`部门编码${value}重复，请重新输入`)) : callback()
    }
    const checkName = async(rule, value, callback) => {
      // 获取最新的数据，拿到全部部门数据
      const { depts } = await getDepartmentsApi()
      // 根据传过来的id过滤得到统计部门数组对象
      let flag
      if (this.formData.id) {
        flag = depts.filter(ele => ele.pid === this.currentNode.pid && ele.id !== this.currentNode.id).some(ele => ele.name === value)
      } else {
        const list = depts.filter(ele => ele.pid === this.currentNode.id)
        // 判断输入的name是否和同级部门数组对象里的name一致，flag表示为重复
        flag = list.some(ele => ele.name === value)
      }
      // 重复的时候就抛出校验信息，否则放行
      flag ? callback(new Error(`部门名称${value}重复，请重新输入`)) : callback()
    }
    return {
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        // 校验name重复性得先拿到部门最新数据，通过传过来的当前点击部门的id对全部部门数据过滤，用输入的name去过滤后的数组对象判断是否重复
        name: [
          { required: true, message: '部门名称必填', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称1-50个字符', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        // 发请求拿最新部门信息，比较code字段
        code: [
          { required: true, message: '部门编码必填', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码1-50个字符', trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人必填', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍必填', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍1-300个字符', trigger: 'blur' }
        ]
      },
      people: [] // 人员列表
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  methods: {
    handlerClose() {
      this.$emit('update:dialogVisible', false)
      this.$refs.deptForm.resetFields() // 重置表单
      // 初始化数据
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    // 获取负责人列表
    async handlerFocus() {
      const res = await getEmployeeSimpleApi()
      this.people = res
    },
    // 点击之后触发的事件
    async handlerSubmit() {
      try {
        await this.$refs.deptForm.validate()
        // 发请求添加部门
        this.formData.id ? await updateDepartmentsApi(this.formData) : await addDepartmentsApi({ ...this.formData, pid: this.currentNode.id })
        // 提示用户添加成功
        this.$message.success(`部门${this.formData.id ? '编辑' : '新增'}成功`)
        // 关闭弹窗
        this.handlerClose()
        // 更新视图层
        this.$parent.getDepartments()
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped lang='scss'>

</style>
